package com.geeke.sys.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang3.StringUtils;

import com.geeke.common.service.CrudService;
import com.geeke.common.data.PageRequest;
import com.geeke.common.data.Parameter;
import com.geeke.config.exception.CommonJsonException;

import com.geeke.sys.dao.PostDao;
import com.geeke.sys.entity.Post;
import com.geeke.utils.ResultUtil;
import com.geeke.utils.constants.ErrorEnum;
import com.google.common.collect.Lists;

/**
 * 岗位表 Service
 * @author
 * @version
 */

@Service("postService")
@Transactional(readOnly = true)
public class PostService extends CrudService<PostDao, Post> {

    @Transactional(readOnly = false)
    @Override
    public Post save(Post post) {
        // 重复性检查
        List<Parameter> params = Lists.newArrayList();
        
        // 岗位编码重复性检查
        params.clear();
        params.add(new Parameter("post.code", "=", post.getCode()));
        params.add(new Parameter("post.del_flag", "=", post.getDelFlag()));

        if(!StringUtils.isBlank(post.getId())) {
          params.add(new Parameter("post.id", "<>", post.getId()));
        }

        if(this.dao.count(new PageRequest(params)) > 0) {
            throw new CommonJsonException(ResultUtil.warningJson(ErrorEnum.E_50001, "已存在相同岗位编码"));
        }
        
        // 岗位名称重复性检查
        params.clear();
        params.add(new Parameter("post.name", "=", post.getName()));
        params.add(new Parameter("post.del_flag", "=", post.getDelFlag()));

        if(!StringUtils.isBlank(post.getId())) {
          params.add(new Parameter("post.id", "<>", post.getId()));
        }

        if(this.dao.count(new PageRequest(params)) > 0) {
            throw new CommonJsonException(ResultUtil.warningJson(ErrorEnum.E_50001, "已存在相同岗位名称"));
        }

        Post postTemp = super.save(post);
        return postTemp;
    }
} 